package solution._0040._0042;

/**
 * Created by chen_snow
 * Date: 2021/5/29 23:14
 * Description: 接雨水
 */
public class Solution {
    public int trap(int[] height) {
        if (height == null || height.length <= 2) {
            return 0;
        }

        int length = height.length;

        int[] left_max = new int[length];
        int[] right_max = new int[length];

        left_max[0] = height[0];
        for (int i = 1; i < length; i++) {
            left_max[i] = Math.max(left_max[i - 1], height[i]);
        }

        right_max[length - 1] = height[length - 1];
        for (int i = length - 2; i >= 0; i--) {
            right_max[i] = Math.max(right_max[i + 1], height[i]);
        }

        int result = 0;
        for (int i = 0; i < length; i++) {
            result += Math.min(left_max[i], right_max[i]) - height[i];
        }
        return result;
    }
}
